//
//  LoginController.swift
//  newshaohuo
//
//  Created by shaohuo on 2018/1/30.
//  Copyright © 2018年 shaohuo. All rights reserved.
//

import Foundation
import SwiftProgressHUD

class LoginController: UIViewController {
    
    @IBOutlet weak var mobileTextField: UITextField!
    
    @IBOutlet weak var testTextField: UITextField!
    
    @IBOutlet weak var testButton: UIButton!
    
    @IBOutlet weak var landingButton: UIButton!
    
    @IBOutlet weak var weixinloginButton: UIButton!
    
    //**********************************************//
    
    @IBOutlet weak var logo_dengluTop: NSLayoutConstraint!
    
    @IBOutlet weak var middleViewTop: NSLayoutConstraint!
    
    @IBOutlet weak var mobileViewTop: NSLayoutConstraint!
    
    @IBOutlet weak var testViewTop: NSLayoutConstraint!
    
    @IBOutlet weak var weixindengluTop: NSLayoutConstraint!
    
    //**********************************************//
    @IBOutlet weak var recordButton: UIButton!
    
    
    var leftTime:Int = 60
    
    var timer :Timer!
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        NotificationCenter.default.addObserver(self,
                                               selector:#selector(weixinAuthorizationSuccess(notification:)),
                                               name: Notification.Name(rawValue: "weixinAuthorizationSuccess"), object: nil)
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: "weixinAuthorizationSuccess"), object: nil)

    }
    
    @objc func weixinAuthorizationSuccess(notification: Notification) {
    
        let code = notification.object
        requestLoginOrregister(type: "login", source: "wx",mobile:"", code: code as! String,captcha:"")
   
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //屏幕适配
//        logo_dengluTop.constant = (logo_dengluTop.constant) * kAutoSizeScaleY
//        middleViewTop.constant = (middleViewTop.constant) * kAutoSizeScaleY
//        weixindengluTop.constant = (weixindengluTop.constant) * kAutoSizeScaleY
//        mobileViewTop.constant = (mobileViewTop.constant) * kAutoSizeScaleY
//        testViewTop.constant = (testViewTop.constant) * kAutoSizeScaleY
        
        //设置按钮边框
        testButton.layer.borderWidth = 0.5
        testButton.layer.borderColor = UIColor.init(hexString: "#B7B7B7").cgColor
        
        landingButton.layer.borderWidth = 0.5
        landingButton.layer.borderColor = UIColor.init(hexString: "#B7B7B7").cgColor

    }
    
    func requestSendCaptcha(type:String,source:String,mobile:String,is_voice:String) -> Void {
        //要加密的数据
        let param = ["command":"sendCaptcha","type":type,"source":source,"mobile":mobile,"is_voice":is_voice]
        
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Login"], successed: { (resultDict) in
            
            SwiftProgressHUD.showOnlyText((resultDict["msg"]) as! String)
        })
    }
    
    
    func requestLoginOrregister(type:String,source:String,mobile:String,code:String,captcha:String) -> Void {
        //要加密的数据
        let param = ["command":"loginOrregister","type":type,"source":source,"mobile":mobile,"code":code,"captcha":captcha,"app_name":"shr"]
        
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Login"], successed: { (resultDict) in
            
            let data = resultDict["data"] as! [String:AnyObject]
            
            if !code.isEmpty {
                
                if (data["is_reg"] as? Int == 1) {
                    
                    let openidStr = data["openid"] as? String
                    let unionidStr = data["unionid"] as? String
                    
                    let bindVc = BindingController()
                    bindVc.openidString = openidStr
                    bindVc.unionidString = unionidStr
                    bindVc.delegate = self
                    self.present(bindVc, animated: true, completion: nil)
                    
                }else {
                    self.saveUserInfo(data: data)
                }
            
            }else {
                self.saveUserInfo(data: data)
            }
        })
    }
    
    //保存用户信息
    func saveUserInfo(data:[String:AnyObject]) {

        //发送通知
 NotificationCenter.default.post(name:NSNotification.Name(rawValue:"loginSuccess"), object: nil, userInfo: nil)
        
        if let uid = data["uid"] as? String {
            UserTicketModel.sharedInstance.uid = uid
        }
        if let token = data["shraccess_token"] as? String {
            UserTicketModel.sharedInstance.token = token
        }
        if let mobile = data["mobile"] as? String {
            UserTicketModel.sharedInstance.phone = mobile
            JPUSHService.setTags([mobile], completion: { (iResCode, iTags, seq) in
                print("极光=\(iResCode),\(iTags!)")
            }, seq: 0)
        }
        if let real_name = data["real_name"] as? String {
            UserTicketModel.sharedInstance.name = real_name
        }
        if let nick_name = data["nick_name"] as? String {
            UserTicketModel.sharedInstance.nick = nick_name
        }
        if let header_img = data["header_img"] as? String {
            UserTicketModel.sharedInstance.headerImg = header_img
        }
        if let signature = data["signature"] as? String {
            UserTicketModel.sharedInstance.perm = signature
        }
        if let type = data["is_shr"] as? String {
            UserTicketModel.sharedInstance.user_type = Int(type)
        }
        
        //默认打开声音
        UserNotificationSettingModel.sharedInstance.is_voice_off = true
        //默认播放男声
        UserNotificationSettingModel.sharedInstance.is_voice_sex = "new_order"
    
        self.dismiss(animated: true, completion: nil)
    }
    
    //返回上一页
    @IBAction func dismissBtnAction(_ sender: UIButton) {
        
        dismiss(animated: true, completion: nil)
    }
    
    //获取验证码
    @IBAction func testBtnAction(_ sender: UIButton) {
        
        if (mobileTextField.text?.isEmpty)! {
            SwiftProgressHUD.showOnlyText("请输入手机号")
        }else {
            
            if ValidatedType.PhoneNumberIsValidated(vStr: mobileTextField.text!) == false {
                SwiftProgressHUD.showOnlyText("输入的手机号不合法")
                return
            }
            
            leftTime = 60
            sender.setTitle("重新计时(\(leftTime)S)", for: .disabled)
            sender.isEnabled = false
            //获取该计时器的剩余时间
            timer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target: self, selector: #selector(tickDown), userInfo: nil, repeats: true)
            
            requestSendCaptcha(type: "login", source: "",mobile:mobileTextField.text!, is_voice: "0")
        }
    }
    
    @objc func tickDown() {
        //将剩余时间减少1秒
        leftTime -= 1
        //修改UIDatePicker的剩余时间
        testButton.setTitle("重新计时(\(leftTime)S)", for: .disabled)
        //如果剩余时间小于等于0
        if leftTime <= 0 {
            //取消定时器
            timer.invalidate()
            testButton.isEnabled = true
            testButton.setTitle("重发短信验证", for: .normal)
        }
    }
    
    //语音验证码
    @IBAction func recordLoginBtnAction(_ sender: UIButton) {
        if (mobileTextField.text?.isEmpty)! {
            SwiftProgressHUD.showOnlyText("请输入手机号")
        }else {
            
            if ValidatedType.PhoneNumberIsValidated(vStr: mobileTextField.text!) == false {
                SwiftProgressHUD.showOnlyText("输入的手机号不合法")
                return
            }
            
            requestSendCaptcha(type: "login", source: "",mobile:mobileTextField.text!, is_voice: "1")
            
        }
        
    }
    
    //立即登陆
    @IBAction func landingBtnAction(_ sender: UIButton) {
        
        if (mobileTextField.text?.isEmpty)! {
           SwiftProgressHUD.showOnlyText("请输入手机号")
        }else if (testTextField.text?.isEmpty)!{
            SwiftProgressHUD.showOnlyText("请输入6位验证码")
        }else {
            requestLoginOrregister(type: "login", source: "mobile",mobile:mobileTextField.text!, code: "",captcha:testTextField.text!)
        }
    }
    
    @IBAction func weixinBtnAction(_ sender: UIButton) {
        
        let req = SendAuthReq()
        req.scope = "snsapi_userinfo"
        req.state = "App"
        WXApi.send(req)
    }
    
}

extension LoginController : BindingControllerDelegate {
    
    func bindingControllerDissmiss() {
        dismiss(animated: false, completion: nil)
    }
    
}
